package com.lb.shopguide.ui.fragment.boss;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.flyco.tablayout.utils.UnreadMsgUtils;
import com.flyco.tablayout.widget.MsgView;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterBossMessage;
import com.lb.shopguide.base.BaseMainFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.BossImMessageBean;
import com.lb.shopguide.entity.BossMessageBean;
import com.lb.shopguide.entity.GuidanceBean;
import com.lb.shopguide.entity.MsgAttachedContent;
import com.lb.shopguide.event.boss.RookieAddGuideEvent;
import com.lb.shopguide.event.boss.RookieAddShopEvent;
import com.lb.shopguide.event.boss.RookieChargeInMoneyEvent;
import com.lb.shopguide.event.boss.RookieSetPtPercentEvent;
import com.lb.shopguide.event.guide.BossSecretaryEvent;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.event.jump.JumpMyActivityFromSecretaryEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.shopguide.im.session.SessionHelper;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.activity.MessageDetailActivity;
import com.lb.shopguide.ui.dialog.DialogMakeSure;
import com.lb.shopguide.ui.fragment.boss.market.FragmentActivityApply;
import com.lb.shopguide.ui.fragment.boss.market.FragmentMarketing;
import com.lb.shopguide.ui.fragment.boss.market.FragmentUseTemplate;
import com.lb.shopguide.ui.view.AppBarStateChangeListener;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/12/23.
 */

public class FragmentSecretary extends BaseMainFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.app_bar)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.layout_logos)
    LinearLayout layoutLogos;
    @BindView(R.id.layout_logos_toolbar)
    LinearLayout layoutLogoToolbar;
    @BindView(R.id.layout_activity)
    LinearLayout layoutActivity;
    @BindView(R.id.layout_customer_service)
    LinearLayout layoutCustomerService;
    @BindView(R.id.layout_message)
    LinearLayout layoutMessage;
    //    @BindView(R.id.layout_marketing)
//    LinearLayout layoutMarketing;
    @BindView(R.id.iv_activity)
    ImageView ivActivity;
    @BindView(R.id.iv_custom_service)
    ImageView ivCustomService;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
//    @BindView(R.id.iv_marketing)
//    ImageView ivMarketing;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.msgview)
    MsgView msgView;
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    private AppBarStateChangeListener mAppBarStateChangeListener;
    private AppBarStateChangeListener.State curState;

    private FragmentRookieGuide fragmentRookieGuide;
    private ArrayList<MultiItemEntity> mBossMessageBeanList;
    private List<RecentContact> mRecentContacts;

    private AdapterBossMessage mAdapter;

    private GuidanceBean guidanceBean;
    private int[] mTopPoint = new int[2], mLayoutLogosPoint = new int[2];


    public static FragmentSecretary newInstance() {
        return new FragmentSecretary();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_secretary;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        mBossMessageBeanList = new ArrayList<>();
        EventBus.getDefault().register(this);
        startRequest();
    }

    private void startRequest() {
        sendRequestGetNoviceGuidance();
        getRecentContact();
        sendRequestGetMessageList();
    }

    @Override
    public void initView() {
        ctb.setTvTitle("身边小秘");
        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view_boss, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无消息");
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });

        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new AdapterBossMessage(mBossMessageBeanList, true);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).paintProvider(mAdapter).build());

        initListener();
    }

    @Override
    public void finishRefresh() {
        swipeRefreshLayout.setRefreshing(false);
        mAdapter.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    private void initListener() {
        mAppBarStateChangeListener = new AppBarStateChangeListener() {

            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                curState = state;
                LogUtils.d("onStateChanged============" + state);
            }

            @Override
            public void onOffsetChanged(State state, float offset) {
                translationView(offset);
                if (offset < 1) {
                    swipeRefreshLayout.setEnabled(true);
                } else {
                    swipeRefreshLayout.setEnabled(false);
                }
            }
        };
        mAppBarLayout.addOnOffsetChangedListener(mAppBarStateChangeListener);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MultiItemEntity entity = mBossMessageBeanList.get(position);
                if (entity instanceof BossMessageBean) {
                    BossMessageBean bossMessageBean = (BossMessageBean) entity;
                    if (bossMessageBean.getMsgItemTypeCode() == AppConstant.MESSAGE_BALANCE_NOT_ENOUGH) {
                        EventBus.getDefault().post(new StartBrotherEvent(FragmentChargeInMoney.newInstance()));
                    } else if (bossMessageBean.getMsgItemTypeCode() == AppConstant.MESSAGE_ACTIVITY_APPLY) {
                        EventBus.getDefault().post(new StartBrotherEvent(FragmentActivityApply.newInstance(bossMessageBean.getMsgAttachedContent().getApplyCode(), bossMessageBean.getMsgAttachedContent().getMsgId())));
                    } else if (bossMessageBean.getMsgItemTypeCode() == AppConstant.MESSAGE_MARKET_ADVICE) {
                        MsgAttachedContent content = bossMessageBean.getMsgAttachedContent();
                        EventBus.getDefault().post(new StartBrotherEvent(FragmentUseTemplate.newInstance(content.getTemplateCode(), content.getTemplateName(), content.getStoreCode(), content.getMsgId())));
                    } else {
                        startToActivityPage(bossMessageBean.getMsgLinkUrl(), bossMessageBean.getMsgTitle());
                    }
                } else if (entity instanceof GuidanceBean) {
                    fragmentRookieGuide = FragmentRookieGuide.newInstance(guidanceBean);
                    EventBus.getDefault().post(new StartBrotherEvent(fragmentRookieGuide));
                }
            }
        });
        mAdapter.setOnMsgCloseListener(new AdapterBossMessage.OnMsgManagerListener() {
            @Override
            public void onMsgClose(final String msgCode) {
                DialogMakeSure dialog = new DialogMakeSure(mContext);
                dialog.getDialog("确定要删除该消息吗?").show();
                dialog.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
                    @Override
                    public void onSure(DialogInterface dialog, int which) {
                        sendRequestCloseMsg(msgCode);
                    }

                    @Override
                    public void onCancel(DialogInterface dialog, int which) {
                    }
                });
            }

            @Override
            public void onImMsgRead() {
                clearRead();
            }

            @Override
            public void onCheckMsg() {
                clearRead();
                MessageDetailActivity.start(mContext, AppConstant.SERVICE_ACCID, SessionHelper.getBossP2pCustomization(AppConstant.SERVICE_ACCID), null);
            }

            @Override
            public void gotoActivity(String url, String title) {
                startToActivityPage(url, title);
            }
        });
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, true);
    }

    @Override
    public String getPageTag() {
        return FragmentSecretary.class.getName();
    }

//    @Override
//    public void onSupportVisible() {
//        super.onSupportVisible();
//        if (mAppBarLayout != null) {
//            mAppBarLayout.addOnOffsetChangedListener(mAppBarStateChangeListener);
//            swipeRefreshLayout.setOnRefreshListener(this);
//        }
//
//    }
//
//    @Override
//    public void onSupportInvisible() {
//        super.onSupportInvisible();
//        mAppBarLayout.removeOnOffsetChangedListener(mAppBarStateChangeListener);
//    }


    @OnClick({R.id.layout_activity, R.id.iv_activity})
    void activityClick() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentBossActivity.newInstance()));
    }

    @OnClick({R.id.layout_customer_service, R.id.iv_custom_service})
    void customServiceClick() {
        clearRead();
        MessageDetailActivity.start(mContext, AppConstant.SERVICE_ACCID, SessionHelper.getBossP2pCustomization(AppConstant.SERVICE_ACCID), null);
    }

    @OnClick({R.id.layout_message, R.id.iv_message})
    void messageClick() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentBossMessage.newInstance()));
    }

//    @OnClick({R.id.layout_marketing, R.id.iv_marketing})
//    void marketingClick() {
//        EventBus.getDefault().post(new StartBrotherEvent(FragmentMarketing.newInstance()));
//    }


    @Override
    public void onResume() {
        super.onResume();
        mTopPoint[0] += ConvertUtils.dp2px(16);
        LogUtils.d("onResume");
    }

    private void sendRequestGetNoviceGuidance() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    guidanceBean = (GuidanceBean) JsonUtil.getObject(response.getReturnContent(), GuidanceBean.class);
                    guidanceBean.setMsgItemTypeCode(AppConstant.MESSAGE_GUIDE_MESSAGE);
                    bindRookieGuide(guidanceBean);
                }
            }
        };
        ApiMethodBoss.getNoviceGuidance(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }


    private void sendRequestGetMessageList() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArrayBossMessage = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonArrayBossMessage.size() != 0) {
                        for (JsonElement obj : jsonArrayBossMessage) {
                            BossMessageBean bean = JsonUtil.getGson().fromJson(obj, BossMessageBean.class);
                            mBossMessageBeanList.add(bean);
                        }
                    }
                    refreshRecyclerView();
                    finishRefresh();
                }
            }
        };
        ApiMethodBoss.getBossMessage(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestCloseMsg(String msgCode) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mBossMessageBeanList = new ArrayList<>();
                    sendRequestGetMessageList();
                    getRecentContact();
                }
            }
        };
        ApiMethodBoss.closeMsg(new SimpleLbObserver(listener, otherListener), msgCode, this, FragmentEvent.DESTROY_VIEW);
    }

    private void clearRead() {
        NIMClient.getService(MsgService.class).clearAllUnreadCount();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getRecentContact();
            }
        }, 200);

    }


    private void translationView(float offset) {
        layoutLogos.getLocationOnScreen(mLayoutLogosPoint);
        float yTitleOffset = -(mLayoutLogosPoint[1] - mTopPoint[1]) * offset;
        setAnim(ivActivity, offset);
        setAnim(ivCustomService, offset);
        setAnim(ivMessage, offset);
//        setAnim(ivMarketing, offset);

        layoutLogoToolbar.setAlpha(offset);
        layoutLogos.setAlpha(1 - offset);
        Log.d("========alpha==", "" + (1 - offset));
        Log.d("========offset==", "" + offset);
        checkToolbarIfClick();
    }

    private void setAnim(View view, float offset) {
        view.setAlpha(offset);
        if (view.getAlpha() < 0.6f) {
            view.setClickable(false);
        } else {
            view.setClickable(true);
        }
    }

    private void checkToolbarIfClick() {
        if (layoutLogos.getAlpha() < 0.8f) {
            layoutActivity.setClickable(false);
            layoutCustomerService.setClickable(false);
            layoutMessage.setClickable(false);
//            layoutMarketing.setClickable(false);
        } else {
            layoutActivity.setClickable(true);
            layoutCustomerService.setClickable(true);
            layoutMessage.setClickable(true);
//            layoutMarketing.setClickable(true);
        }
    }

    private void getRecentContact() {
        // 查询最近联系人列表数据
        NIMClient.getService(MsgService.class).queryRecentContacts().setCallback(new RequestCallbackWrapper<List<RecentContact>>() {

            @Override
            public void onResult(int code, List<RecentContact> recents, Throwable exception) {
                if (code != com.netease.nimlib.sdk.ResponseCode.RES_SUCCESS || recents == null) {
                    return;
                }
                mRecentContacts = recents;
                // 此处如果是界面刚初始化，为了防止界面卡顿，可先在后台把需要显示的用户资料和群组资料在后台加载好，然后再刷新界面
                if (isAdded()) {
                    onRecentContactsLoaded();
                }
            }
        });
    }

    private void bindRookieGuide(GuidanceBean bean) {
        if (!bean.isFinished()) {
            mBossMessageBeanList.add(guidanceBean);
            refreshRecyclerView();
        }
        if (fragmentRookieGuide != null) {
            fragmentRookieGuide.refreshRookieGuide(bean);
        }
    }


    private void onRecentContactsLoaded() {
        if (mBossMessageBeanList.size() != 0) {
            ArrayList<MultiItemEntity> list = new ArrayList<>();
            for (MultiItemEntity entity : mBossMessageBeanList) {
                if (entity instanceof BossImMessageBean) {
                    list.add(entity);
                }
            }
            mBossMessageBeanList.removeAll(list);
        }
        int unReadNum = 0;
        for (int i = 0; i < mRecentContacts.size(); i++) {
            RecentContact contact = mRecentContacts.get(i);
            if (contact.getUnreadCount() != 0) {
                unReadNum += contact.getUnreadCount();
                BossImMessageBean msgBean = new BossImMessageBean();
                msgBean.setTime(contact.getTime());
                msgBean.setMsgContent(contact.getContent());
                msgBean.setMsgItemTypeCode(AppConstant.MESSAGE_IM_MESSAGE);
                mBossMessageBeanList.add(msgBean);
            }
        }
        if (unReadNum != 0) {
            UnreadMsgUtils.show(msgView, unReadNum);
        } else {
            msgView.setVisibility(View.GONE);
        }
        refreshRecyclerView();
    }

    private void refreshRecyclerView() {
        sortMsg();
        if (mBossMessageBeanList.size() != 0) {
            mAdapter.setNewData(mBossMessageBeanList);
        } else {
            bindEmpty();
        }
    }

    private void sortMsg() {
        Collections.sort(mBossMessageBeanList, new Comparator<MultiItemEntity>() {
            @Override
            public int compare(MultiItemEntity o1, MultiItemEntity o2) {
                long time1 = 0;
                if (o1 instanceof BossImMessageBean) {
                    time1 = ((BossImMessageBean) o1).getTime();
                } else if (o1 instanceof BossMessageBean) {
                    time1 = TimeUtils.string2Millis(((BossMessageBean) o1).getCreateTime());
                } else if (o1 instanceof GuidanceBean) {
                    return -1;
                }
                long time2 = 0;
                if (o2 instanceof BossImMessageBean) {
                    time2 = ((BossImMessageBean) o2).getTime();
                } else if (o2 instanceof BossMessageBean) {
                    time2 = TimeUtils.string2Millis(((BossMessageBean) o2).getCreateTime());
                } else if (o2 instanceof GuidanceBean) {
                    return 1;
                }
                if (time1 > time2) {
                    return -1;
                } else if (time1 < time2) {
                    return 1;
                }
                return 0;
            }
        });
    }

    private void bindEmpty() {
        mAdapter.setNewData(mBossMessageBeanList);
        mAdapter.setEmptyView(noDataView);
    }

    private void startToActivityPage(String url, String name) {
        Intent intent = new Intent(mContext, ActivityActivityDetail.class);
        Bundle bundle = new Bundle();
        if (url.contains("?")) {
            bundle.putString(AppConstant.WEB_URL, url + "&token=" + mUserConfigManager.getUserToken() + "&type=android");
        } else {
            bundle.putString(AppConstant.WEB_URL, url + "?token=" + mUserConfigManager.getUserToken() + "&type=android");
        }
        if (!TextUtils.isEmpty(name)) {
            bundle.putString(AppConstant.WEB_TITLE, name);
        }
        intent.putExtras(bundle);
        startActivity(intent);
    }


    @Subscribe
    public void onAddGuide(RookieAddGuideEvent event) {
        onRefresh();
    }

    @Subscribe
    public void onAddGuide(RookieAddShopEvent event) {
        onRefresh();
    }

    @Subscribe
    public void onAddGuide(RookieSetPtPercentEvent event) {
        onRefresh();
    }

    @Subscribe
    public void onAddGuide(RookieChargeInMoneyEvent event) {
        onRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBossMsgRefresh(BossSecretaryEvent event) {
        onRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void jumpMyActivity(JumpMyActivityFromSecretaryEvent event) {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentMarketing.newInstance(true)));
    }


    @Override
    public void onDestroyView() {
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, false);
        incomingMessageObserver = null;
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh() {
        mBossMessageBeanList = new ArrayList<>();
        startRequest();
    }

    Observer<List<IMMessage>> incomingMessageObserver = new Observer<List<IMMessage>>() {
        @Override
        public void onEvent(List<IMMessage> messages) {
            // 处理新收到的消息，为了上传处理方便，SDK 保证参数 messages 全部来自同一个聊天对象。
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getRecentContact();
                }
            }, 200);
        }
    };
}
